import { createRouter, createWebHashHistory } from 'vue-router'
import type {
  Router,
  RouteLocationNormalized,
  RouteRecordNormalized,
  RouteRecordRaw
} from 'vue-router'
import { isUrl } from '@/utils/is'
import { omit, cloneDeep } from 'lodash-es'

const modules = import.meta.glob('../views/**/*.{vue,tsx}')

/* Layout */
export const Layout = () => import('@/layout/Layout.vue')

export const getParentLayout = () => {
  return () =>
    new Promise((resolve) => {
      resolve({
        name: 'ParentLayout'
      })
    })
}

export const getRawRoute = (route: RouteLocationNormalized): RouteLocationNormalized => {
  if (!route) return route
  const { matched, ...opt } = route
  return {
    ...opt,
    matched: (matched
      ? matched.map((item) => ({
          meta: item.meta,
          name: item.name,
          path: item.path
        }))
      : undefined) as RouteRecordNormalized[]
  }
}

// 后端控制路由生成（后端已根据角色过滤菜单）
export const generateRoutesByServer = (routes: AppCustomRouteRecordRaw[]): AppRouteRecordRaw[] => {
  const res: AppRouteRecordRaw[] = []

  console.log('=== 开始处理后端菜单数据 ===')
  console.log('输入数据:', routes)
  console.log('输入数据类型:', typeof routes, '长度:', routes?.length)

  for (const route of routes) {
    console.log('--- 处理单个菜单项 ---')
    console.log('原始菜单项:', route)

    // 字段映射：正确映射后端返回的菜单数据字段
    const path = route.path || route.menuRoute || route.routePath || route.url || ''
    const name = route.name || route.menuName || route.routeName || ''
    const redirect = route.redirect || route.redirectPath || ''

    console.log('字段映射结果:', {
      path: { 原始: route.path, menuRoute: route.menuRoute, 最终: path },
      name: { 原始: route.name, menuName: route.menuName, 最终: name },
      redirect: { 原始: route.redirect, redirectPath: route.redirectPath, 最终: redirect }
    })

    // 如果缺少必要的字段，跳过这个路由
    if (!path) {
      console.warn('路由生成：跳过无效路由，缺少path字段:', { path, route })
      continue
    }

    // 检查是否有子菜单
    const hasChildren = route.children && Array.isArray(route.children) && route.children.length > 0
    const childrenCount = hasChildren && route.children ? route.children.length : 0
    console.log('菜单项是否有子菜单:', hasChildren, '子菜单数量:', childrenCount)

    // 组件字段映射：支持更多可能的字段名
    let component = route.component || route.componentPath || route.page || route.view || ''

    // 如果component仍然为空，尝试从其他字段推断
    if (!component) {
      // 尝试从path推断组件路径
      if (path && path !== '/') {
        // 将路径转换为组件路径，例如：/system -> System
        const pathParts = path.split('/').filter((p) => p)
        if (pathParts.length > 0) {
          const lastPart = pathParts[pathParts.length - 1]
          // 首字母大写，转换为PascalCase
          component = lastPart.charAt(0).toUpperCase() + lastPart.slice(1)
          console.log('路由生成：从path推断component:', { path, inferredComponent: component })
        }
      }

      // 如果还是没有component，尝试从name推断
      if (!component && name) {
        // 将中文名称转换为英文组件名
        const componentMap: Record<string, string> = {
          系统管理: 'System',
          菜单管理: 'Menu',
          用户管理: 'User',
          角色管理: 'Role',
          部门管理: 'Department',
          字典管理: 'Dict',
          仪表盘: 'Dashboard',
          分析页: 'Analysis',
          工作台: 'Workplace'
        }

        if (componentMap[name]) {
          component = componentMap[name]
          console.log('路由生成：从name推断component:', { name, inferredComponent: component })
        }
      }
    }

    console.log('路由生成：处理路由对象:', {
      原始path: route.path,
      原始menuRoute: route.menuRoute,
      原始name: route.name,
      原始menuName: route.menuName,
      原始component: route.component,
      映射后path: path,
      映射后name: name,
      映射后component: component,
      是否有子菜单: hasChildren
    })

    // 如果component为空，根据是否有子菜单来决定
    if (!component) {
      if (hasChildren && route.children) {
        // 如果有子菜单，使用Layout作为父级组件
        component = '#'
        console.log('路由生成：使用Layout作为父级组件:', {
          path,
          component,
          子菜单数量: route.children.length
        })
      } else {
        console.warn('路由生成：跳过无效路由，缺少component字段且无子菜单:', {
          path,
          component,
          route
        })
        continue
      }
    }

    const data: AppRouteRecordRaw = {
      path: path,
      name: name || `route_${Date.now()}_${Math.random()}`, // 如果没有name，生成一个唯一的name
      redirect: redirect,
      meta: {
        title: name, // 使用菜单名称作为标题
        icon: route.menuIcon, // 使用菜单图标
        hidden: false, // 默认显示
        permission: route.menuCode ? [route.menuCode] : [], // 使用菜单编码作为权限
        // 保留其他元数据
        ...route.meta
      },
      children: [] // 确保children属性始终是数组
    }

    console.log('生成的路由对象:', data)

    // 设置组件
    if (component) {
      if (component === '#') {
        // 使用Layout作为父级组件
        data.component = Layout
        console.log('路由生成：设置Layout组件:', { path, component })
      } else {
        const comModule = modules[`../${component}.vue`] || modules[`../${component}.tsx`]
        if (!comModule) {
          console.error(`未找到${component}.vue文件或${component}.tsx文件，请创建`)
          // 如果找不到组件文件，但有子菜单，使用Layout
          if (hasChildren) {
            data.component = Layout
            console.log('路由生成：组件文件未找到，使用Layout:', { path, component })
          } else {
            console.warn('路由生成：跳过路由，组件文件未找到且无子菜单:', { path, component })
            continue
          }
        } else {
          // 动态加载路由文件
          data.component = comModule
          console.log('路由生成：设置动态组件:', { path, component })
        }
      }
    }

    // 递归处理子菜单
    if (hasChildren && route.children) {
      console.log('处理子菜单，数量:', route.children.length)
      const childRoutes = generateRoutesByServer(route.children)
      console.log('子菜单处理结果:', childRoutes)

      if (childRoutes && childRoutes.length > 0) {
        data.children = childRoutes
        console.log('设置子菜单成功，数量:', data.children.length)
      } else {
        console.warn('子菜单处理失败，没有生成有效的子路由')
      }
    }

    res.push(data as AppRouteRecordRaw)
    console.log('已添加路由到结果数组，当前总数:', res.length)
  }

  console.log('=== 菜单数据处理完成 ===')
  console.log('最终生成的路由:', res)
  return res
}

export const pathResolve = (parentPath: string, path: string) => {
  if (isUrl(path)) return path
  const childPath = path.startsWith('/') || !path ? path : `/${path}`
  return `${parentPath}${childPath}`.replace(/\/\//g, '/').trim()
}

// 路由降级
export const flatMultiLevelRoutes = (routes: AppRouteRecordRaw[]) => {
  const modules: AppRouteRecordRaw[] = cloneDeep(routes)
  for (let index = 0; index < modules.length; index++) {
    const route = modules[index]
    if (!isMultipleRoute(route)) {
      continue
    }
    promoteRouteLevel(route)
  }
  return modules
}

// 层级是否大于2
const isMultipleRoute = (route: AppRouteRecordRaw) => {
  if (!route || !Reflect.has(route, 'children') || !route.children?.length) {
    return false
  }

  const children = route.children

  let flag = false
  for (let index = 0; index < children.length; index++) {
    const child = children[index]
    if (child.children?.length) {
      flag = true
      break
    }
  }
  return flag
}

// 生成二级路由
const promoteRouteLevel = (route: AppRouteRecordRaw) => {
  let router: Router | null = createRouter({
    routes: [route as RouteRecordRaw],
    history: createWebHashHistory()
  })

  const routes = router.getRoutes()
  addToChildren(routes, route.children || [], route)
  router = null

  route.children = route.children?.map((item) => omit(item, 'children'))
}

// 添加所有子菜单
const addToChildren = (
  routes: RouteRecordNormalized[],
  children: AppRouteRecordRaw[],
  routeModule: AppRouteRecordRaw
) => {
  for (let index = 0; index < children.length; index++) {
    const child = children[index]
    const route = routes.find((item) => item.name === child.name)
    if (!route) {
      continue
    }
    routeModule.children = routeModule.children || []
    if (!routeModule.children.find((item) => item.name === route.name)) {
      routeModule.children?.push(route as unknown as AppRouteRecordRaw)
    }
    if (child.children?.length) {
      addToChildren(routes, child.children, routeModule)
    }
  }
}
